package com.zhanpple.color_picker.library

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View

/**
 * @author zhangmingping
 * @date 2022/2/22 11:04 上午
 * des:色调选择器
 */
class ColorHuaPicker @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {
    private val mPaint = Paint(Paint.ANTI_ALIAS_FLAG)
    private val mLinePaint = Paint(Paint.ANTI_ALIAS_FLAG)

    private val mHalfLightWidth by lazy {
        ScreenSizeUtils.dp2px(2F, resources)
    }

    private val mPaddingV by lazy {
        ScreenSizeUtils.dp2px(5F, resources)
    }
    private var mDy = 0F

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        mDy = measuredHeight - mPaddingV * 2
        setColorShader()
    }

    private fun setColorShader() {
        val linearShader = LinearGradient(
            0F,
            mPaddingV, 0F,
            measuredHeight.toFloat() - mPaddingV,
            getColorH(),
            null,
            Shader.TileMode.CLAMP
        )
        mPaint.shader = linearShader
        postInvalidate()
    }


    /**
     * 创建光谱
     */
    private fun getColorH(): IntArray {
        val intArrayOf = IntArray(361)
        repeat(361) {
            intArrayOf[it] = Color.HSVToColor(floatArrayOf(it.toFloat(), 1f, 1f))
        }
        return intArrayOf
    }

    var mHuaFloat = 0F
        set(value) {
            if (field != value) {
                field = value
                postInvalidate()
            }
        }

    /**
     * 设置当前色值
     * @param color 取颜色色值hua
     */
    fun setCurrentColor(color: Int, back: Boolean = false) {
        val floatArray = FloatArray(3)
        Color.colorToHSV(color, floatArray)
        mHuaFloat = floatArray[0]
        if (back) {
            mColorHueBack?.invoke(mHuaFloat)
        }
    }

    @SuppressLint("ClickableViewAccessibility")
    override fun onTouchEvent(event: MotionEvent): Boolean {
        val y = event.y - mPaddingV
        mHuaFloat = (y / mDy).coerceAtMost(1F).coerceAtLeast(0F) * 360
        mColorHueBack?.invoke(mHuaFloat)
        return true
    }

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        canvas?.drawRect(0F, 0F, measuredWidth.toFloat(), measuredHeight.toFloat(), mPaint)
        mLinePaint.color = Color.WHITE
        canvas?.drawRect(
            0F,
            mHuaFloat * mDy / 360 - mHalfLightWidth + mPaddingV,
            measuredWidth.toFloat(),
            mHuaFloat * mDy / 360 + mHalfLightWidth + mPaddingV,
            mLinePaint
        )

    }

    var mColorHueBack: ((Float) -> Unit)? = null
}